package com.stars.easyms.feign.request;

import com.alibaba.fastjson.JSON;
import feign.RequestTemplate;
import feign.codec.Encoder;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.Map;

/**
 * <p>className: EasyMsGetFeignEncoder</p>
 * <p>description: Get方式的feign解析器</p>
 *
 * @author guoguifang
 * @version 1.6.2
 * @date 2020/9/2 11:23 下午
 */
@SuppressWarnings("unchecked")
class EasyMsGetFeignEncoder implements Encoder {

    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) {
        Map<String, Object> paramMap = object instanceof Map ? (Map<String, Object>) object : JSON.parseObject(JSON.toJSONString(object));
        paramMap.forEach((key, value) -> {
            if (StringUtils.isNotBlank(key) && value != null && StringUtils.isNotBlank(value.toString())) {
                try {
                    String encodeKey = URLEncoder.encode(key, "utf-8");
                    String encodeValue = URLEncoder.encode(value.toString(), "utf-8");
                    template.query(encodeKey, encodeValue);
                } catch (UnsupportedEncodingException e) {
                    // ignore
                }
            }
        });
    }

}
